 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=102 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:03 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Assert use cases
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='dbc,debug,design,invariant,test,assertion,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Assert use cases</div>

<div class='main-body'>
 
<br>Here are some common examples of using the <tt>assert</tt> keyword
:
<ul>
<li>
pre-conditions (in private methods only) - the requirements which a method
requires its caller to fulfill</li>

<li>
post-conditions - verify the promises made by a method to its caller</li>

<li>
class invariants - validate object state</li>

<li>
unreachable-at-runtime code - parts of your program which you expect to
be unreachable, but which cannot be verified as such at compile-time (often
<tt>else</tt>
clauses and default cases in <tt>switch</tt> statements)</li>
</ul>
<b>Example</b>
<br>
<PRE>

<span class='keyword'>import</span> java.util.Random;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> Flower {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String... arguments) {
    <span class='keyword'>final</span> Flower tulip = <span class='keyword'>new</span> Flower(<span class='literal'>"Tulip"</span>, <span class='literal'>1</span>);
    tulip.grow();
    tulip.grow();
    System.out.println( tulip );

    tulip.randomGrowOrWither();
    System.out.println( tulip );

    tulip.wither();
    tulip.wither();
    System.out.println( tulip );
  }

  <span class='comment'>/**
  * @param aSpecies must have content.
  * @param aInitialLength must be greater than 0.
  */</span>
  <span class='keyword'>public</span> Flower( <span class='keyword'>final</span> String aSpecies, <span class='keyword'>final</span> <span class='keyword'>int</span> aInitialLength ) {
    <span class='comment'>//assert is NOT used to validate params of public methods
</span>    <span class='keyword'>if</span> ( !isValidSpecies(aSpecies) ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Species must have content."</span>);
    }
    <span class='keyword'>if</span> ( !isValidLength(aInitialLength) ) {
      <span class='keyword'>throw</span> <span class='keyword'>new</span> IllegalArgumentException(<span class='literal'>"Initial length must be positive."</span>);
    }

    fSpecies = aSpecies;
    fLength = aInitialLength;

    <span class='comment'>//check the class invariant
</span>    assert hasValidState(): <span class='literal'>"Construction failed - not valid state."</span>;
  }

  <span class='keyword'>public</span> <span class='keyword'>boolean</span> isMature() {
    <span class='keyword'>return</span> fLength &gt; <span class='literal'>5</span> ;
    <span class='comment'>//not necessary to assert valid state here, since
</span>    <span class='comment'>//the state has not changed.
</span>  }

  <span class='comment'>/**
  * Increase the length by at least one unit.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>void</span> grow(){
    <span class='comment'>//this style of checking post-conditions is NOT recommended,
</span>    <span class='comment'>//since the copy of fLength is always made, even when
</span>    <span class='comment'>//assertions are disabled.
</span>    <span class='comment'>//See &lt;code&gt;wither&lt;/code&gt; (below) for an example with an improved style.
</span>    <span class='keyword'>final</span> <span class='keyword'>int</span> oldLength = fLength;
    fLength += getLengthIncrease( fLength );
    <span class='comment'>//post-condition: length has increased
</span>    assert (fLength &gt; oldLength);

    <span class='comment'>//check the class invariant
</span>    assert hasValidState(): <span class='keyword'>this</span>;
  }

  <span class='comment'>/**
  * Decrease the length by one unit, but only if the resulting length
  * will still be greater than 0.
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>void</span> wither() {

    <span class='comment'>//this local class exists only to take a snapshot of the current state.
</span>    <span class='comment'>//although bulky, this style allows post-conditions of arbitrary complexity.
</span>    <span class='keyword'>class</span> OriginalState {
      OriginalState() {
        fOriginalLength = fLength;
      }
      <span class='keyword'>int</span> getLength() {
        <span class='keyword'>return</span> fOriginalLength;
      }
      <span class='keyword'>private</span> <span class='keyword'>final</span> <span class='keyword'>int</span> fOriginalLength;
    }
    OriginalState originalState = <span class='keyword'>null</span>;
    <span class='comment'>//construct object inside an assertion, in order to ensure that
</span>    <span class='comment'>//no construction takes place when assertions are disabled.
</span>    <span class='comment'>//this assert is rather unusual in that it will always succeed, and in that
</span>    <span class='comment'>//it has side-effects - it creates an object and sets a reference
</span>    assert( (originalState = <span class='keyword'>new</span> OriginalState()) != <span class='keyword'>null</span>);

    <span class='keyword'>if</span> (fLength &gt; <span class='literal'>1</span>) {
      --fLength;
    }

    <span class='comment'>//post-condition: length has decreased by one or has remained the same
</span>    assert( fLength <= originalState.getLength() );

    <span class='comment'>//check the class invariant
</span>    assert hasValidState(): <span class='keyword'>this</span>;
  }

  <span class='comment'>/**
  * Randomly select one of three actions
  * &lt;ul&gt;
  * &lt;li&gt;do nothing
  * &lt;li&gt;grow
  * &lt;li&gt;wither
  * &lt;/ul&gt;
  */</span>
  <span class='keyword'>public</span> <span class='keyword'>void</span> randomGrowOrWither() {
    <span class='comment'>//(magic numbers are used here instead of symbolic constants
</span>    <span class='comment'>//to slightly clarify the example)
</span>    Random generator = <span class='keyword'>new</span> Random();
    <span class='keyword'>int</span> action =  generator.nextInt(<span class='literal'>3</span>);
    <span class='comment'>//according to the documentation for the Random class, action
</span>    <span class='comment'>//should take one of the values 0,1,2.
</span>    <span class='keyword'>if</span> ( action == <span class='literal'>0</span> ) {
      <span class='comment'>//do nothing
</span>    }
    <span class='keyword'>else</span> <span class='keyword'>if</span> ( action == <span class='literal'>1</span> ) {
      grow();
    }
    <span class='keyword'>else</span> <span class='keyword'>if</span> ( action == <span class='literal'>2</span> ) {
      wither();
    }
    <span class='keyword'>else</span> {
      <span class='comment'>//this is still executed if assertions are disabled
</span>      <span class='keyword'>throw</span> <span class='keyword'>new</span> AssertionError(<span class='literal'>"Unexpected value for action: "</span> + action);
    }
    <span class='comment'>//check the class invariant
</span>    assert hasValidState(): <span class='keyword'>this</span>;
  }

  <span class='comment'>/**
  * Use for debugging only.
  */</span>
  <span class='keyword'>public</span> String toString(){
    <span class='keyword'>final</span> StringBuilder result = <span class='keyword'>new</span> StringBuilder();
    result.append( <span class='keyword'>this</span>.getClass().getName() );
    result.append( <span class='literal'>": Species="</span>  );
    result.append( fSpecies );
    result.append( <span class='literal'>" Length="</span> );
    result.append( fLength );
    <span class='keyword'>return</span> result.toString();
  }

  <span class='comment'>// PRIVATE ////
</span>  <span class='keyword'>private</span> <span class='keyword'>final</span> String fSpecies;
  <span class='keyword'>private</span> <span class='keyword'>int</span> fLength;

  <span class='comment'>/**
  * Implements the class invariant.
  *
  * Perform all checks on the state of the object.
  * One may assert that this method returns true at the end
  * of every public method.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>boolean</span> hasValidState(){
    <span class='keyword'>return</span> isValidSpecies(fSpecies) &amp;&amp; isValidLength(fLength);
  }

  <span class='comment'>/**
  * Species must have content.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>boolean</span> isValidSpecies( <span class='keyword'>final</span> String aSpecies ) {
    <span class='keyword'>return</span> aSpecies != <span class='keyword'>null</span> &amp;&amp; aSpecies.trim().length()&gt;<span class='literal'>0</span>;
  }

  <span class='comment'>/**
  * Length must be greater than 0.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>boolean</span> isValidLength( <span class='keyword'>final</span> <span class='keyword'>int</span> aLength ) {
    <span class='keyword'>return</span> aLength &gt; <span class='literal'>0</span>;
  }

  <span class='comment'>/**
  * Length increase depends on current length.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>int</span> getLengthIncrease( <span class='keyword'>int</span> aOriginalLength ) {
    <span class='comment'>//since this is a private method, an assertion
</span>    <span class='comment'>//may be used to validate the argument
</span>    assert aOriginalLength &gt; <span class='literal'>0</span>: <span class='keyword'>this</span>;
    <span class='keyword'>int</span> result = <span class='literal'>0</span>;
    <span class='keyword'>if</span> ( aOriginalLength &gt; <span class='literal'>10</span> ) {
      result = <span class='literal'>2</span>;
    }
    <span class='keyword'>else</span> {
      result = <span class='literal'>1</span>;
    }
    assert (result &gt; <span class='literal'>0</span>):result;
    <span class='keyword'>return</span> result;
  }
}
 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction0d31-2.html?Id=6'>Validate state with class invariants</a> <br>
 
  
  <a href='TopicAction63b6-2.html?Id=194'>Design by Contract</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='102'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=102 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:03 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
